package com.hulman.oms.web;

import com.hulman.oms.bean.Device;
import com.hulman.oms.bean.Result;
import com.hulman.oms.bean.Task;
import com.hulman.oms.bean.WorkTask;
import com.hulman.oms.service.DeviceService;
import com.hulman.oms.service.WorkTaskService;
import com.hulman.oms.util.NumberUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: maxwellens
 */
@RestController
public class WorkTaskController
{
    @Autowired
    private WorkTaskService workTaskService;
    @Autowired
    private DeviceService deviceService;

    @GetMapping("/work-tasks/{id}")
    public Result findWorkTaskById(@PathVariable Integer id)
    {
        WorkTask workTask = workTaskService.findWorkTaskById(id);
        return new Result(workTask);
    }

    @GetMapping("/work-tasks")
    public Result findWorkTasks(Integer page, Integer limit, Integer createById, String createByName, String content, String startTime, Integer state, Integer deviceId)
    {
        Map<String, Object> map = new HashMap<>();
        map.put("page", page);
        map.put("limit", limit);
        map.put("createById", createById);
        map.put("createByName", createByName);
        map.put("content", content);
        map.put("startTime", startTime);
        map.put("state", state);
        if (deviceId != null)
        {
            Device device = deviceService.findDeviceById(deviceId);
            map.put("deviceName", device.getName());
        }
        return workTaskService.findWorkTasksResult(map);
    }

    @DeleteMapping("/work-tasks/{ids}")
    public Result deleteWorkTaskById(@PathVariable String ids)
    {
        int[] idArrays = NumberUtil.parseIntArray(ids);
        for (Integer id : idArrays)
        {
            workTaskService.deleteWorkTaskById(id);
        }
        return Result.SUCCESS;
    }

    @PostMapping("/work-tasks/create")
    public Result create(String devices, String locations, String content)
    {
        Task task = workTaskService.create(devices, locations, content);
        return new Result(task);
    }

    @PostMapping("/work-tasks/complete")
    public Result complete(Integer taskId, Integer id, String completion)
    {
        workTaskService.complete(taskId, id, completion);
        return Result.SUCCESS;
    }

    @PostMapping("/work-tasks/terminate")
    public Result terminate(Integer id)
    {
        workTaskService.terminate(id);
        return Result.SUCCESS;
    }

}
